#include "DataBaseManager.h"

namespace Jonathan
{
   DataBaseManager* DataBaseManager::s_Instance = 0;

   /**
    * @brief Gets the instance of the database manager.
    *
    * @return Jonathan::DataBaseManager * Database manager instance.
    */
   DataBaseManager* DataBaseManager::GetInstance ()
   {
      if (!s_Instance)
         s_Instance = new DataBaseManager();

      return s_Instance;
   }


   /**
    * @brief Adds a database to work with.
    *
    * @param dbPath Path to database.
    * @param bookTree Tree widget for books.
    * @param referenceTree Tree widget for reference material.
    * @return TreeItem_Book* Newly created book tree widget item, null if unable to create.
    */
   TreeItem_Book* DataBaseManager::AddBook (QString dbPath, QTreeWidget* bookTree, QTreeWidget* referenceTree)
   {      
      QSqlDatabase db = this->GetDatabase (dbPath);
      QSqlQuery query = db.exec ("SELECT * FROM book_info;");
      if (query.next ())
      {
         QSqlRecord record = query.record ();
         QString type = record.value ("Type").toString ();
         if (type == "Reference")
         {
            TreeItem_Book *book = new TreeItem_Book (dbPath, db, record, referenceTree);
            this->m_ReferenceBooks.append (book);
            return book;
         }
         else if (type == "TSK")
         {
         }
         else if (type == "Daily")
         {
         }
         else
         {
            TreeItem_Book *book = new TreeItem_Book (dbPath, db, record, bookTree);
            this->m_Books.append (book);
            return book;
         }
      }
      else
         db.close ();

      return NULL;
   }

   /**
    * @brief Gets the list of books.
    *
    * @return QList<TreeItem_Book*> List of books.
    */
   QList<TreeItem_Book*> DataBaseManager::GetBooks ()
   {
      return this->m_Books;
   }

   /**
    * @brief Gets the list of reference books.
    *
    * @return QList<TreeItem_Book*> List of reference books.
    */
   QList<TreeItem_Book*> DataBaseManager::GetReferenceBooks ()
   {
      return this->m_ReferenceBooks;
   }

   /**
    * @brief Gets a connection to the given database.
    *
    * @param dbPath Path to database to get.
    * @return QSqlDatabase SQLite database connection.
    */
   QSqlDatabase DataBaseManager::GetDatabase (QString dbPath)
   {
      QSqlDatabase db;
      if (QSqlDatabase::contains (dbPath))
         db = QSqlDatabase::database (dbPath);
      else
         db = QSqlDatabase::addDatabase ("QSQLITE", dbPath);
      db.setDatabaseName (dbPath);
      db.open ();
      return db;
   }
}
